package com.vchello.controller.project;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.baomidou.mybatisplus.plugins.Page;
import com.vchello.bean.bind.ProjectQuery;
import com.vchello.bean.file.Folder;
import com.vchello.bean.lib.Area;
import com.vchello.bean.lib.Field;
import com.vchello.bean.lib.Round;
import com.vchello.bean.lib.Unit;
import com.vchello.bean.pro.InvestNote;
import com.vchello.bean.pro.Pro;
import com.vchello.bean.pro.ProFollow;
import com.vchello.bean.pro.ProLables;
import com.vchello.bean.pro.ProMilepost;
import com.vchello.bean.pro.ProOrganization;
import com.vchello.bean.pro.ProjectChange;
import com.vchello.bean.user.Invitation;
import com.vchello.bean.user.User;
import com.vchello.bean.user.UserArea;
import com.vchello.bean.user.UserField;
import com.vchello.bean.user.UserProgress;
import com.vchello.controller.BaseController;
import com.vchello.service.file.FolderService;
import com.vchello.service.lib.AreaService;
import com.vchello.service.lib.FieldService;
import com.vchello.service.lib.RoundService;
import com.vchello.service.lib.UnitService;
import com.vchello.service.project.ProjectService;
import com.vchello.service.user.UserService;
import com.vchello.thead.RemoveInvitationThread;
import com.vchello.util.ToolUtil;
import com.vchello.util.UploadFileHelper;
import com.vchello.util.Utility;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/projects")
public class ProjectContrller extends BaseController{

	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoundService roundService;
	@Autowired
	private UnitService unitService;
	@Autowired
	private AreaService areaService; 
	@Autowired
	private FolderService folderService;
	@Autowired
	private FieldService fieldService;
	@Autowired
	private RemoveInvitationThread removeInvitation;
	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
	
	private static final String REDIRECT_LOGIN = "redirect:/login";
	
	@RequestMapping(value = "/list", method=RequestMethod.GET)
	public String project(Page<Pro> page, ProjectQuery query, Model model){
		User user = (User) session.getAttribute("user");

		if(user == null){
			return REDIRECT_LOGIN;
		}
		//List<UserProgress> _upList = projectService.userProgressesList(user.getId());
		user = userService.findByOne(user.getId());
		
		//dubbo增加
		/**
		 * 基础数据
		 */
		//查询数据
		List<Round> roundList = roundService.findAll();
		List<Unit> unitList = unitService.findAll();
		
		//机构
		if(user.getType()==1){
			//左边进度栏统计
			//1.个人部分
			List<Object[]> statisProgress = projectService.statisProgressV2(user.getUserProgressList(), user.getId());
			//查询全部个数
			Long allDataCount = projectService.allDataCounForInvestor(user.getId());
			//3.构建进度集合
			List<UserProgress> upList = projectService.userProgressesList(user.getId());
			//4.构建负责人
			List<Object[]> dealmans = userService.findDealman(user.getId());
			
			model.addAttribute("statisProgress", statisProgress).addAttribute("upList", upList)
			.addAttribute("allDataCount", allDataCount);
			
			//查询项目列表
			query.setUserId(user.getId());
			query.setUserType(user.getType());
			page.setSize(12);;
			Page<Pro> pages = projectService.queryPage(page, query);
			
			model.addAttribute("user", user).addAttribute("roundList", roundList).addAttribute("unitList", unitList)
			.addAttribute("pages", pages).addAttribute("query", query).addAttribute("dealmans", dealmans);
			
			return "/project/projects-manager-organize";
		}
		
		//个人投资者
		if(user.getType()==2){
			//左边进度栏统计
			//1.个人部分
			List<UserProgress> userUpList =  projectService.userProgressesList(user.getId());
			List<Object[]> statisProgress = projectService.statisProgressV2(userUpList, user.getId());
			//查询全部个数
			Long allDataCount = projectService.allDataCounForInvestor(user.getId());
			//2.个人共享机构部分
			List<Object[]> statisProgressOrganize = projectService.statisOganizeProgress(user.getId());
			//3.构建进度集合
			List<UserProgress> upList = projectService.userProgressesList(user.getId());
			//4.构建机构空项目进度
			List<Object[]> organizeProgress = null;
			if(userService.findParentUserByUserId(user.getId())!=null){
				organizeProgress =  projectService.findOrganizeProgress(userService.findParentUserByUserId(user.getId()).getId(), user.getId());
			}
			
			model.addAttribute("statisProgress", statisProgress).addAttribute("_statisProgress", statisProgress).addAttribute("upList", upList)
			.addAttribute("allDataCount", allDataCount).addAttribute("statisProgressOrganize", statisProgressOrganize).addAttribute("organizeProgress", organizeProgress);
			
			//查询项目列表
			query.setUserId(user.getId());
			query.setUserType(user.getType());
			page.setSize(12);
			Page<Pro> pages = projectService.queryPage(page, query);
			
			model.addAttribute("user", user).addAttribute("roundList", roundList).addAttribute("unitList", unitList)
			.addAttribute("pages", pages).addAttribute("query", query);
			
			return "/project/projects-manager-invester";
		}
		return REDIRECT_LOGIN;
	}
	
	/**
	 * 异步请求数据
	 * @param page
	 * @param query
	 */
	@RequestMapping(value = "/projectData", method = RequestMethod.POST)
	public void projectData(Page<Pro> page, ProjectQuery query) {
		User user = (User) session.getAttribute("user");
		user = userService.findByOne(user.getId());
		//项目列表
		query.setUserId(user.getId());
		query.setUserType(user.getType());
		page.setSize(12);
		Page<Pro> pages = projectService.queryPage(page, query);
		
		JSONObject jsonObject = dataToJson(pages, query, user);
		success(jsonObject);
	}
	
	/**	
	 * 增加/修改  进度名称
	 * @param userProgress
	 */
	@RequestMapping(value = "/changeProgress" , method = RequestMethod.POST)
	public void addOrUpdateUserProgress(UserProgress userProgress){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return;
		}
		userProgress.setUserId(Long.valueOf(user.getId()));
		userProgress.setSort(projectService.queryProgressSort(user.getId()));
		userProgress.setProgressType(1);
		if(userProgress.getId()!=0){
			String name = userProgress.getName();
			userProgress = projectService.findUserProgressById(userProgress.getId());
			userProgress.setName(name);
		}
		boolean flag =projectService.saveOrUpdateProgress(userProgress);
		if (flag) {
			success(userProgress.getId()+"");;
			return;
		}
		returnFalse();
	}
	
	/**
	 * 修改项目的进度状态
	 * @param proId
	 * @param progressId
	 */
	@RequestMapping(value = "/changeProjectProgress" , method = RequestMethod.POST)
	public void changeProjectProgress(int proId, int progressId){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return;
		}
		Pro pro = projectService.findProjectById(proId);
		int oldUserId  = pro.getUserId();
		pro.setProgressId(progressId);
		if(projectService.findUserProgressById(progressId).getUserId()!=user.getId()){
			pro.setUserId(userService.findParentUserByUserId(user.getId()).getId());
			//管理project_change表
			ProjectChange projectChange = projectService.findProjectChangeByProId(proId);
			if(projectChange!=null){
				projectChange.setUserProgressId(progressId);
			}else{
				projectChange = new ProjectChange(user.getId(), userService.findParentUserByUserId(user.getId()).getId(), proId, progressId);
			}
			projectService.saveOrUpdateProjectChange(projectChange);
		}else{
			//如果转入自己的进度
			//1.判断项目本身是不是属于自己的，如果本身属于自己的不需要操作project_change，如果本身不属于自己的需要删除project_change数据并且把项目所有者修改为自己
			if(pro.getUserId()!=user.getId()){
				pro.setUserId(user.getId());
				ProjectChange projectChange = projectService.findProjectChangeByProId(proId);
				projectService.deleteProjectChange(projectChange);
			}
		}
		//项目归属人发生变化的是时候，需要更换项目文档的父级ID以及userId
		if(oldUserId!=user.getId()){
			
		}
		boolean flag = projectService.saveOrUpdateProject(pro);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 更新跟进人
	 * @param ids
	 * @param proId
	 */
	@RequestMapping(value = "/updateFollow" , method = RequestMethod.POST)
	public void updateFollow(@RequestParam(value="ids[]",required=false) int[] ids, int proId){
		boolean flag = projectService.updateFollow(ids, proId);
		if(flag){
			Pro pro = projectService.findProjectById(proId);
			List<ProFollow> list = pro.getProFollowList();
			JSONObject json = new JSONObject();
			JSONArray arry = new JSONArray();
			for(ProFollow f : list){
				JSONObject fJson = new JSONObject();
				fJson.put("id", f.getUserId());
				fJson.put("name", userService.findByOne(f.getUserId()).getUserName());
				arry.add(fJson);
			}
			json.put("follow", arry);
			success(json);
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 修改项目的优先级
	 * @param proId
	 * @param progressId
	 */
	@RequestMapping(value = "/changeProjectUnit" , method = RequestMethod.POST)
	public void changeProjectUnit(int proId, int unitId){
		Pro pro = projectService.findProjectById(proId);
		pro.setUnit(unitId);
		boolean flag = projectService.saveOrUpdateProject(pro);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 检查进度是否能删除
	 * @param prograssId
	 */
	@RequestMapping(value = "/checkPrograss", method = RequestMethod.POST)
	public void checkPrograss(int prograssId){
		boolean flag = projectService.checkPrograss(prograssId);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 删除进度
	 * @param prograssId
	 */
	@RequestMapping(value = "/deletePrograss", method = RequestMethod.POST)
	public void deletePrograss(int prograssId){
		boolean flag = projectService.deletePrograss(prograssId);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 进入新增页面并且初始化数据
	 */
	@RequestMapping(value = "/addProject", method = RequestMethod.GET)
	public String returnAddView(Model model, int type){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return REDIRECT_LOGIN;
		}
		user = userService.findByOne(user.getId());
		
		//查询数据
		List<Round> roundList = roundService.findAll();
		List<Area> areaList = areaService.findAll();
		List<Field> fieldList = fieldService.findAll();
		
		if(type==2){
			User parentUser = userService.findParentUserByUserId(user.getId());
			model.addAttribute("parentUser", parentUser);
		}
		model.addAttribute("user", user).addAttribute("roundList", roundList).addAttribute("areaList", areaList).addAttribute("fieldList", fieldList).addAttribute("type", type);
		return "/project/add-project";
	}
	
	/**
	 * 删除项目
	 * @param id
	 */
	@RequestMapping(value= "/deletePro", method = RequestMethod.GET)
	public void deleteProject(int id){
		boolean flag = projectService.deleteProject(id);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 新建项目
	 * @param pro
	 * @param tagsArry
	 */
	@RequestMapping(value = "/addProject", method = RequestMethod.POST)
	public void addProject(Pro pro, @RequestParam(value="tagsArry[]",required=false) String[] tagsArry, int userProType){
		
		User user = (User) session.getAttribute("user");
		if(user == null){
			returnFalse();
		}
		try {
			//处理附件
			//LOGO
			if(null!=pro.getLogo()&&!"".equals(pro.getLogo())){
				String logo = UploadFileHelper.isFileExists(pro.getLogo(), request);
				if(ToolUtil.isEmpty(logo)){
					returnFalse();
					return;
				}
				pro.setLogo(logo);
			}
			//BP
			if(null!=pro.getBp()&&!"".equals(pro.getBp())){
				String bp = UploadFileHelper.isFileExists(pro.getBp(), request);
				if(ToolUtil.isEmpty(bp)){
					returnFalse();
					return;
				}
				pro.setBp(bp);
			}

			/*if(userProType==1){
				pro.setUserId(user.getId());
			}else{
				pro.setUserId(userService.findParentUserByUserId(user.getId()).getId());
			}*/
			pro.setUserId(user.getId());
			pro.setCreateTime(Utility.getDateNowFromformatStr("yyyy-MM-dd HH:mm:ss"));
			pro.setUnit(0);
			pro.setType(1);
			pro.setHide(1);
			pro.setProgressId(0);
			boolean flag = projectService.saveOrUpdate(pro);
			if(flag){
				//处理项目标签
				List<ProLables> labelList = new ArrayList<ProLables>();
				if(tagsArry!=null&&tagsArry.length>0){
					for(String labelName : tagsArry){
						ProLables label = new ProLables(labelName, pro.getId());
						labelList.add(label);
					}
					projectService.saveProLabels(labelList);
				}
				//设置默认跟进人，当为机构项目的时候
				/*if(userProType==2){
					ProFollow pf = new ProFollow(user.getId(), pro.getId());
					projectService.saveProFollow(pf);
				}*/
			}
			if(flag){
				returnSuccess();
			}else{
				returnFalse();
			}
		} catch (IOException e) {
			returnFalse();
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 截取投资人头像
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 * @param url
	 */
	@RequestMapping(value="/cutLogo", method = RequestMethod.POST)
	public void cutLogo(int x, int y, int width, int height, String url){
		try {
			if(width ==0 || height == 0 || (!StringUtils.isNotBlank(url))){
				error("参数错误");
				return;
			}
			String path = request.getSession().getServletContext().getRealPath("/")+StringEscapeUtils.unescapeHtml4(url);
			File file = new File(path);
			if(file.exists() && file.isFile()){
				String urlpath = cutImage(file, x, y, width, height,path,url);
				if(StringUtils.isNotBlank(urlpath)){
					success(StringEscapeUtils.unescapeHtml4(urlpath));
				}
			}else{
				error("文件不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			error("剪切出错,文件可能有损坏");
		}
	}
	
	/**
	 * 详情内页更新头像
	 * @param pro
	 * @param tagsArry
	 */
	@RequestMapping(value = "/updateLogo", method = RequestMethod.POST)
	public void updateLogo(int proId, String url){
		try {
			//处理附件
			//LOGO
			Pro pro =  projectService.findProjectById(proId);
			if(null!=url&&!"".equals(url)){
				String logo = UploadFileHelper.isFileExists(url, request);
				if(ToolUtil.isEmpty(logo)){
					returnFalse();
					return;
				}
				pro.setLogo(logo);
			}
			boolean flag = projectService.saveOrUpdate(pro);
			if(flag){
				returnSuccess();
			}else{
				returnFalse();
			}
		} catch (IOException e) {
			returnFalse();
			e.printStackTrace();
		}
	}
	
	/**
     * 截图
     * @param img
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     */
    public String cutImage(File file, int x, int y, int width, int height, String path, String url) {
    	String newPath = "";
        try {
        	int index = file.getName().lastIndexOf(".");
        	if(index == -1)
        		return "";
        	String endPath = file.getName().substring(index+1);
        	Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(endPath);
        	ImageReader reader = it.next();
        	// 获取图片流
        	ImageInputStream  iis = ImageIO.createImageInputStream(file);
        	reader.setInput(iis, true);
        	ImageReadParam param = reader.getDefaultReadParam();
            /*
             * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象
             * 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。
             */
            Rectangle rect = new Rectangle(x, y, width, height);
            // 提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion(rect);
            /*
             * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象，并将 它作为一个完整的
             * BufferedImage 返回。
             */
            BufferedImage bi = reader.read(0, param);
            // 保存新图片
            newPath = path+"."+endPath;
            ImageIO.write(bi, endPath, new File(newPath));
            newPath = url +"."+endPath;
        } catch (Exception e) {
            e.printStackTrace();
            error("图片格式有损，无法截图");
        }
        return newPath;
    }
	/**
	 * 项目详情
	 * @return
	 */
	@RequestMapping(value = "/projectDetail/{id}", method = RequestMethod.GET)
	public String projectDetail(@PathVariable int id, Model model){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return REDIRECT_LOGIN;
		}
		user = userService.findByOne(user.getId());
		
		Pro project = projectService.findProjectById(id);
		List<Round> roundList = roundService.findAll();
		List<Unit> unitList = unitService.findAll();
		List<Area> areaList = areaService.findAll();
		List<Field> fieldList = fieldService.findAll();
		
		//标识当前项目是否是属于个人项目 0： 个人 1：机构
/*		int proType = 0;
		if(project.getUserId()!=user.getId()){
			User parentUser = userService.findParentUserByUserId(user.getId());
			proType=1;
			model.addAttribute("parentUser", parentUser);
		}
		//跟进人权限
		int authorization = 0;
		for(ProFollow p : project.getProFollowList()){
			if(p.getUser().getId() == user.getId()  || project.getUserId()==user.getId()){
				authorization = 1;
			}
		}
		if(proType==0){
			authorization = 1;
		}*/
		
		//构建进度集合
		List<UserProgress> upList = projectService.userProgressesList(user.getId());
		model.addAttribute("user", user).addAttribute("project",project).addAttribute("roundList", roundList).addAttribute("fieldList", fieldList)
		.addAttribute("unitList", unitList).addAttribute("areaList", areaList).addAttribute("upList", upList);
		
		return "/project/projects-detail";
	}
	
	/**
	 * 项目基础模块更新
	 * @param pro
	 * @param tagsArry
	 */
	@RequestMapping(value = "/updateProject", method = RequestMethod.POST)
	public void updateProject(Pro pro, @RequestParam(value="tagsArry[]",required=false) String[] tagsArry){
		Pro project = projectService.findProjectById(pro.getId());
		
		try {
			if(null!=pro.getBp()&&!"".equals(pro.getBp())){
				String bp = UploadFileHelper.isFileExists(pro.getBp(), request);
				if(ToolUtil.isEmpty(bp)){
					returnFalse();
					return;
				}
				project.setBp(bp);
			}
			project.setName(pro.getName());
			project.setAreaId(pro.getAreaId());
			project.setProDetail(pro.getProDetail());
			project.setRoundId(pro.getRoundId());
			project.setFieldId(pro.getFieldId());
			project.setMoney(pro.getMoney());
			project.setCurrency(pro.getCurrency());
			project.setStock(pro.getStock());
			project.setLink(pro.getLink());
			boolean flag = projectService.updatePro(project);
			boolean isSuccess = false;
			if(flag){
				folderService.updateFolderByProjectId(pro.getId(), pro.getName());
				//更新跟进人
				if(projectService.deleteProlabels(pro.getId())){
					List<ProLables> labelList = new ArrayList<ProLables>();
					if(tagsArry!=null){
						for(String labelName : tagsArry){
							ProLables label = new ProLables(labelName, pro.getId());
							labelList.add(label);
						}
						isSuccess = projectService.saveProLabels(labelList);
					}else{
						isSuccess = true;
					}
				}
			}
			if(isSuccess){
				returnSuccess();
			}else{
				returnFalse();
			}
		} catch (IOException e) {
			e.printStackTrace();
			returnFalse();
		}
	}
	
	/**
	 * 更新项目里程
	 * @param proMileposts
	 */
	@RequestMapping(value = "/updateMilepost", method = RequestMethod.POST)
	public void updateMilepost(@RequestBody List<ProMilepost> proMileposts){
		boolean flag = projectService.updateMilepost(proMileposts);
		if(flag){
			success(proMileposts.get(0).getId()+"");
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 删除里程碑
	 * @param id
	 */
	@RequestMapping(value = "/deleteMilepost/{id}", method = RequestMethod.GET)
	public void deleteMilepost(@PathVariable int id){
		ProMilepost mile = projectService.findProMilepostById(id);
		boolean flag = projectService.deleteMilepost(mile);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 更新团队人员
	 * @param proMileposts
	 */
	@RequestMapping(value = "/updateOrganiza", method = RequestMethod.POST)
	public void updateOrganiza(@RequestBody List<ProOrganization> proOrganizations){
		boolean flag = projectService.updateOrganizations(proOrganizations);
		if(flag){
			success(proOrganizations.get(0).getId()+"");
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 删除团队信息
	 * @param id
	 */
	@RequestMapping(value = "/deleteOrganiza/{id}", method = RequestMethod.GET)
	public void deleteOrganiza(@PathVariable int id){
		ProOrganization mile = projectService.findProOrganizaById(id);
		boolean flag = projectService.deleteOrganiza(mile);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 查找跟进人
	 * @param keyWord
	 */
	@RequestMapping(value = "/invitations", method = RequestMethod.POST)
	public void getInvitations(String keyWord){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return;
		}
		int userId = user.getId();
		if(user.getType()==2){
			userId =userService.findParentUserByUserId(userId).getId();
		}
		List<Invitation> invitationList = projectService.getInvitationList(userId, keyWord);
		if(invitationList.size()>0){
			JSONObject invJson = new JSONObject();
			JSONArray jsons = new JSONArray();
			for(Invitation inv : invitationList){
				JSONObject json = new JSONObject();
				json.put("id", inv.getReceiveUser().getId());
				json.put("name", inv.getReceiveUser().getUserName());
				jsons.add(json);
			}
			invJson.put("status", true);
			invJson.put("data", jsons);
			success(invJson);
			return;
		}
		returnFalse();
	}

	/**
	 * 跟新跟进人
	 * @param proFollows
	 */
	@RequestMapping(value = "/changeFollow", method = RequestMethod.POST)
	public void changeFollowFollow(@RequestBody List<ProFollow> proFollows){
		if(proFollows!=null&&proFollows.size()>0){
			boolean flag = projectService.updateFollow(proFollows);
			if(flag){
				returnSuccess();
				return;
			}
		}
		returnFalse();
	}
	
	/**
	 * 投资笔记
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/projectNoteView/{id}", method = RequestMethod.GET)
	public String projectNoteView(@PathVariable int id, Model model){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return REDIRECT_LOGIN;
		}
		user = userService.findByOne(user.getId());

		//3.构建进度集合
		List<UserProgress> upList = projectService.userProgressesList(user.getId());
		
		List<Unit> unitList = unitService.findAll();		
		Pro project = projectService.findProjectById(id);
		//标识当前项目是否是属于个人项目 0： 个人 1：机构
		int proType = 0;
		if(project.getUserId()!=user.getId()){
			User parentUser = userService.findParentUserByUserId(user.getId());
			proType=1;
			model.addAttribute("parentUser", parentUser);
		}
		int authorization = 0;
		for(ProFollow p : project.getProFollowList()){
			if(p.getUser().getId() == user.getId() || project.getUserId()==user.getId()){
				authorization = 1;
			}
		}
		if(proType==0){
			authorization = 1;
		}
		
		model.addAttribute("user", user).addAttribute("project", project).addAttribute("unitList", unitList).addAttribute("upList", upList)
		.addAttribute("proType", proType).addAttribute("authorization", authorization);
		return "/project/investment-notes";
	}
	
	/**
	 * 保存 更新 投资人笔记
	 * @param investNote
	 */
	@RequestMapping(value = "/saveOrUpdateNote", method = RequestMethod.POST)
	public void saveOrUpdateNote(InvestNote investNote){
		investNote =  projectService.saveOrUpdateNote(investNote);
		JSONObject json = new JSONObject();
		json.put("create", investNote.getCreateTimeView());
		json.put("update", investNote.getUpdateTimeView());
		json.put("id", investNote.getId());
		success(json);
	}
	
	/**
	 *删除投资人笔记 
	 * @param id
	 */
	@RequestMapping(value = "/deleteNote/{id}", method = RequestMethod.GET)
	public void deleteNote(@PathVariable int id){
		boolean flag = projectService.delNote(id);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 其他文档
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/projectFile/{id}", method = RequestMethod.GET)
	public String projectFileView(@PathVariable int id, Model model){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return REDIRECT_LOGIN;
		}
		user = userService.findByOne(user.getId());

		//3.构建进度集合
		List<UserProgress> upList = projectService.userProgressesList(user.getId());
		List<Unit> unitList = unitService.findAll();
		
		Pro project = projectService.findProjectById(id);
		Folder folder = folderService.findByProjectIdAndParentIdAndUserId(project.getId(), folderService.findProjectFoldByUserId(project.getUserId()).getId(), project.getUserId());
		
		//标识当前项目是否是属于个人项目 0： 个人 1：机构
		int proType = 0;
		if(project.getUserId()!=user.getId()){
			User parentUser = userService.findParentUserByUserId(user.getId());
			proType=1;
			model.addAttribute("parentUser", parentUser);
		}
		int authorization = 0;
		for(ProFollow p : project.getProFollowList()){
			if(p.getUser().getId() == user.getId() || project.getUserId()==user.getId()){
				authorization = 1;
			}
		}
		if(proType==0){
			authorization = 1;
		}
		
		model.addAttribute("folder", folder).addAttribute("user", user).addAttribute("project", project).addAttribute("upList", upList)
		.addAttribute("unitList", unitList).addAttribute("proType", proType).addAttribute("authorization", authorization);
		
		return "/project/project-document";
	}
	
	/**
	 * 尽调文档
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/projectInvestigateFile/{id}", method = RequestMethod.GET)
	public String projectInvestigateFileView(@PathVariable int id, Model model){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return REDIRECT_LOGIN;
		}
		user = userService.findByOne(user.getId());

		//3.构建进度集合
		List<UserProgress> upList = projectService.userProgressesList(user.getId());
		List<Unit> unitList = unitService.findAll();
				
		Pro project = projectService.findProjectById(id);
				
		Folder folder = folderService.findByProjectIdAndParentIdAndUserId(project.getId(), folderService.findProjectInvestigateFoldByUserId(project.getUserId()).getId(), project.getUserId());
		
		//标识当前项目是否是属于个人项目 0： 个人 1：机构
		int proType = 0;
		if(project.getUserId()!=user.getId()){
			User parentUser = userService.findParentUserByUserId(user.getId());
			proType=1;
			model.addAttribute("parentUser", parentUser);
		}
		int authorization = 0;
		for(ProFollow p : project.getProFollowList()){
			if(p.getUser().getId() == user.getId() || project.getUserId()==user.getId()){
				authorization = 1;
			}
		}
		if(proType==0){
			authorization = 1;
		}
		
		model.addAttribute("folder", folder).addAttribute("user", user).addAttribute("project", project).addAttribute("upList", upList)
		.addAttribute("unitList", unitList).addAttribute("proType", proType).addAttribute("authorization", authorization);
		
		return "/project/project-investigate";
	}
	
	/**
	 * 查询地区
	 * @param keyWord
	 */
	@RequestMapping(value = "/searchArea", method = RequestMethod.POST)
	public void searchArea(String keyWord){
		List<Area> list = areaService.searchArea(keyWord);
		if(list.size()>0){
			JSONObject json = new JSONObject();
			JSONArray arry = new JSONArray();
			for(Area area : list){
				JSONObject one = new JSONObject();
				one.put("id", area.getId());
				one.put("name", area.getName());
				arry.add(one);
			}
			json.put("list", arry);
			success(json);
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 更新地区
	 * @param arrays
	 */
	@RequestMapping(value = "/updataAreas" , method = RequestMethod.POST)
	public void updateAreas(@RequestParam(value= "arrays[]", required=false)  int[] arrays){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return;
		}
		List<UserArea> dList = projectService.findUserArea(user.getId());
		boolean flag = projectService.updateAreas(arrays, user.getId(), dList);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	/**
	 * 更新领域
	 * @param arrays
	 */
	@RequestMapping(value = "/updateFields" , method = RequestMethod.POST)
	public void updateFields(@RequestParam(value= "arrays[]", required=false)  int[] arrays){
		User user = (User) session.getAttribute("user");
		if(user == null){
			return;
		}
		List<UserField> dList = projectService.findUserField(user.getId());
		boolean flag = projectService.updateFields(arrays, user.getId(), dList);
		if(flag){
			returnSuccess();
		}else{
			returnFalse();
		}
	}
	
	@RequestMapping(value = "/test" , method = RequestMethod.GET)
	public void test(){
		removeInvitation.setInvestorId(5);
		removeInvitation.setOrganizetionId(1);
		threadPoolTaskExecutor.execute(removeInvitation);
	}
	
	/**
	 * 重构Json
	 * @param page
	 * @param query
	 * @return
	 */
	private JSONObject dataToJson(Page<Pro> page, ProjectQuery query, User user){
		JSONObject total = new JSONObject();
		total.put("query", query);
		total.put("pageNo", page.getCurrent());
		total.put("pageSize", page.getSize());
		total.put("totalCount", page.getTotal());
		total.put("totalPages", page.getPages());
		JSONArray jsonArray = new JSONArray();
		for(Pro pro : page.getRecords()){
			JSONObject proJson = new JSONObject();
			proJson.put("id", pro.getId());
			proJson.put("name", pro.getName());
			proJson.put("proUserId", pro.getUserId());
			proJson.put("areaName", pro.getArea()!=null?pro.getArea().getName():"");
			proJson.put("rounName", pro.getRound()!=null?pro.getRound().getName():"");
			proJson.put("fieldName", pro.getField()!=null?pro.getField().getFieldName():"");
			proJson.put("stock", pro.getStock());
			proJson.put("money", pro.getMoney());
			proJson.put("progress", pro.getUserProgress()!=null?pro.getUserProgress().getName():"");
			proJson.put("progressId", pro.getUserProgress()!=null?pro.getUserProgress().getId():0);
			proJson.put("unit", pro.getUnitvo()!=null?pro.getUnitvo().getName():"");
			proJson.put("unitId", pro.getUnitvo()!=null?pro.getUnitvo().getId():0);
			proJson.put("logo", pro.getLogo());
			proJson.put("followName", pro.getProFollowList().size()>0?pro.getProFollowList().get(0).getUser().getUserName():"请选择");
			proJson.put("dealman", pro.getProjectChange()!=null?pro.getProjectChange().getUser().getUserName():"");
			//跟进人
			JSONArray follows = new JSONArray();
			int authorization = 0;
			for(ProFollow p : pro.getProFollowList()){
				JSONObject follow = new JSONObject();
				follow.put("id", p.getUser().getId());
				follow.put("name", p.getUser().getUserName());
				follows.add(follow);
				if(user.getId()==p.getUserId()){
					authorization = 1;
				}
			}
			//机构登录全部有权限
			if(user.getId()==pro.getUserId()){
				authorization = 1;
			}
			//0：自己项目  1：机构项目
			int proType = 0;
			if(user.getType()==1 || pro.getUserId() != user.getId()){
				proType = 1;
			}
			proJson.put("authorization", authorization);
			proJson.put("proType", proType);
			proJson.put("follows", follows);
			jsonArray.add(proJson);
		}
		total.put("dataJson", jsonArray);
		return total;
	}
}
